import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'

const endpoint = process.env.S3_ENDPOINT || ''
const region = process.env.S3_REGION || 'us-east-1'
const accessKeyId = process.env.S3_ACCESS_KEY || ''
const secretAccessKey = process.env.S3_SECRET_KEY || ''
const bucket = process.env.S3_BUCKET || ''
const publicBase = process.env.S3_ENDPOINT_EXTERNAL || ''

export const hasS3 = () =>
  !!endpoint && !!accessKeyId && !!secretAccessKey && !!bucket

let s3: S3Client | null = null
export const s3Client = () => {
  if (!s3) {
    s3 = new S3Client({
      region,
      endpoint,
      forcePathStyle: true,
      credentials: { accessKeyId, secretAccessKey },
    })
  }
  return s3!
}

export async function uploadBufferToS3(key: string, body: Buffer, contentType?: string) {
  const client = s3Client()
  await client.send(new PutObjectCommand({
    Bucket: bucket,
    Key: key,
    Body: body,
    ContentType: contentType,
    ACL: 'private',
  }))
  // 生成对外可访问 URL（基于外网 endpoint）
  const base = publicBase || endpoint
  const normalizedBase = base.replace(/\/+$/, '')
  return `${normalizedBase}/${bucket}/${encodeURIComponent(key)}`
}